<?php
namespace tp5_lib\install\logic;

use tp5_lib\common\logic\Logic;
use think\Exception;

/**
 * 动态配置文件
 */
class DynamicConfig extends Logic
{
    protected $root_dir="";//保存目录，必须有读写权限
    public $category="";//分类，分类保存的目录，可以多级
    public $format="";//格式和扩展名，json/php
    public function __construct($category, $format="json")
    {
        $this->root_dir=env("runtime_path");
        $this->category=$category;
        $this->format=$format;
    }
    static public function alloc($category, $format="json")
    {
        $instance=new static($category, $format);
        return $instance;
    }
    protected function makesureDir()
    {
        $path = $this->root_dir . "/" . $this->category;
        if(file_exists($path))
            return $path;
        if(!file_exists($this->root_dir))
            mkdir($this->root_dir);
        mkdir($path);
        return $path;
    }
    /**
     * 读取动态配置文件
     * @param string $name 配置文件名称(不带扩展名)
     * @return array
     */
    public function read($name)
    {
        $dir=$this->makesureDir();
        $path=$dir."/$name.json";
        if(!file_exists($path)){
            throw new Exception("文件不存在",-1);
        }
        if($this->format === "json"){
            $content=file_get_contents($path);
            return json_decode($content,true);
        }
        elseif($this->format === "php"){
            return include $path;
        }
    }
    /**
     * 写入动态配置文件
     * @param string $name 配置文件名称(不带扩展名)
     * @param array $config
     */
    public function write($name,$config)
    {
        $dir=$this->makesureDir();
        $path=$dir."/$name.json";
        if($this->format === "json"){
            $content=json_encode($config,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
            return file_put_contents($path,$content);
        }
        elseif($this->format === "php"){
            $config="return " . var_export($config, true);
            return include $path;
        }
    }
}
